var express = require('express');
var router = express.Router();
//引入Query.js连接数据库
const Query = require('../tools/Query')
//引入token
const jwt = require('jsonwebtoken')
//引入
const useToken = require('../tools/token')
//引入fs模块
let fs = require('fs')
//引入path模块
const path = require('path')
//引入formidable模块
const formidable = require('formidable')
//引入cors模块
const cors = require('cors')
//引入时间模块
const time = require('time-stamp')



//
// router.use((req,res,next)=>{
//     //接收从前端传过来的token
//     let token = '这是token锁'
//     //正确的话返回为真 token无效
//     if(!useToken.verifyToken(token)){
//         next({
//             msg:'token无效'
//         })
//         return
//     }
//     next()
// })

//获取用户信息
router.get('/user',async(req,res)=>{
    //某个用户
    let mid = `e9b9972f-387c-40ec-87dc-3a0881627784`
    //userStr
    let userStr = `SELECT * FROM e_member WHERE mid='${mid}'`
    //接收
    let [,user] = await Query(userStr)
    delete user[0].password
    user[0].head_photo_url = 'http://localhost:3000/'+ 'uploads/userHead/' + `${user[0].head_photo_url}`
    res.send(user)
})




//更新头像
router.post('/uploadhead',(req,res)=>{
    //update更改数据库中的图片路径
    //将文件放在暂存区

    let form = formidable({
        uploadDir:"stage"
    })

    //上传文件
    form.parse(req,async(err,fields,files)=>{
        //获取文件名字的后缀
        let extName = path.extname(files.f.name)
        //找到原文件名
        let source = path.join(__dirname,'../',files.f.path)
        //生成一个随机的文件名
        let newFileName = time('YYYYMMDDHHmmss') + (Math.random() + '').slice(2,8) + extName
        //新文件名
        let newPath = path.join(__dirname,'../uploads/userHead',newFileName)
        //通过fs.renameSync(old,new)将文件从暂存区剪切到指定文件夹
        fs.renameSync(source,newPath)
        //返回提示提交成功
        res.send({
            msg:'提交成功',
        })

        //将新的文件路径更新到数据库
        let pullPath = `UPDATE e_member SET head_photo_url='${newFileName}' WHERE mid='e9b9972f-387c-40ec-87dc-3a0881627784'`
        //执行
        await Query(pullPath)
    })
})


module.exports = router;
